import React, { forwardRef, useImperativeHandle, useState } from 'react';

import { Form, FormProps, Input, InputNumber, Modal, ModalProps, TreeSelect } from 'antd';

import { store } from '@/store';

import { orgDeptInfoAdd, orgDeptInfoEdit } from '@/services/base/bumenguanlibumenxiangguanjiekou';

import { BizObject, DeptDataNode } from '.';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {
  treeData: DeptDataNode[];
};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = ({ treeData, ...rest }, ref) => {
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async ({ password, _password, ...values }) => {
    const query = {
      ...values,
      pid: values.pid ?? 0
    };

    if (args?.type === 'edit' && args.rowData) {
      query.id = args.rowData.id;
    }

    await (args?.type === 'edit' ? orgDeptInfoEdit(query) : orgDeptInfoAdd(query));

    args?.onSuccess?.();
    setOpen(false);
    store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
  };

  const onClose = () => {
    form.resetFields();
    setOpen(false);
  };

  const afterOpenChange: ModalProps['afterOpenChange'] = (open) => {
    if (open) {
      // 编辑回填数据
      if ((args?.type === 'edit' || args?.type === 'detail') && args?.rowData) {
        // 回填数据
        form.setFieldsValue({
          ...args.rowData,
          // 若pid为0，则说明是根部门，则不显示上级部门
          pid: args.rowData.pid?.toString() === '0' ? undefined : args.rowData.pid
        });
      } else {
        form.resetFields();
        form.setFieldsValue({
          sort: 1
        });
      }
    }
  };

  return (
    <Modal
      afterOpenChange={afterOpenChange}
      title={
        {
          add: '新增部门',
          edit: '编辑部门',
          detail: '部门详情'
        }[args?.type as string]
      }
      width={500}
      {...rest}
      open={open}
      onCancel={onClose}
      onOk={() => {
        form.submit();
      }}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <Form.Item
          name="pid"
          label="上级部门"
          // rules={[
          //   {
          //     required: true,
          //     message: '请选择上级部门',
          //   }
          // ]}
        >
          <TreeSelect placeholder="请选择上级部门" treeData={treeData} allowClear />
        </Form.Item>

        <Form.Item
          name="deptName"
          label="部门名称"
          rules={[
            {
              required: true,
              message: '请输入部门名称'
            }
          ]}
        >
          <Input placeholder="请输入部门名称" allowClear />
        </Form.Item>

        <Form.Item
          name="sort"
          label="排序"
          rules={[
            {
              required: true,
              message: '请输入排序'
            }
          ]}
        >
          <InputNumber placeholder="请输入排序" min={1} step={1} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item label="部门描述" name="description">
          <Input.TextArea placeholder="请输入部门描述" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default forwardRef(Edit);
